package com.business_clean.ui.fragment.addproject;


import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.business_clean.app.App;
import com.business_clean.app.base.BaseFragment;
import com.business_clean.app.callback.OnDialogSelectListener;
import com.business_clean.app.callback.OnDialogTimePickerListener;
import com.business_clean.app.config.Constant;
import com.business_clean.app.config.ConstantMMVK;
import com.business_clean.app.ext.CommonUtils;
import com.business_clean.app.uitl.ActivityForwardUtil;
import com.business_clean.app.uitl.ChoosePicUtil;
import com.business_clean.app.uitl.MMKVHelper;
import com.business_clean.app.uitl.ToastUtil;
import com.business_clean.app.uitl.UploadFileHelper;
import com.business_clean.app.weight.dialog.CustomTimePickerPopup;
import com.business_clean.data.mode.group.GroupMangerEntity;
import com.business_clean.data.mode.group.GroupMangerListEntity;
import com.business_clean.data.mode.job.JobEntity;
import com.business_clean.data.mode.job.JobListEntity;
import com.business_clean.data.mode.members.IDCardMemberEntity;
import com.business_clean.data.mode.members.MembersDetailEntity;
import com.business_clean.data.mode.members.WorkInfoEntity;
import com.business_clean.data.mode.permission.PermissionData;
import com.business_clean.data.mode.project.ProjectMangerList;
import com.business_clean.databinding.FragmentBankCardBinding;
import com.business_clean.databinding.FragmentEmployBinding;
import com.business_clean.ui.activity.custom.AddProjectActivity;
import com.business_clean.ui.activity.group.GroupManagerActivity;
import com.business_clean.ui.activity.permissions.PermissionsActivity;
import com.business_clean.ui.activity.project.AddCompanyProjectActivity;
import com.business_clean.ui.activity.project.ProjectManagerActivity;
import com.business_clean.ui.adapter.GridImageAdapter;
import com.business_clean.viewmodel.request.ProjectMembersViewModel;
import com.business_clean.viewmodel.request.ProjectPersonnelViewModel;
import com.luck.picture.lib.decoration.MyGridSpacingItemDecoration;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.lxj.xpopup.interfaces.OnSelectListener;

import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import me.hgj.mvvmhelper.base.BaseViewModel;
import me.hgj.mvvmhelper.net.LoadStatusEntity;

/**
 * 用工信息
 */
public class EmploymentInformationFragment extends BaseFragment<ProjectMembersViewModel, FragmentEmployBinding> {

    private GridImageAdapter mUploadAdapter;

    private String project_uuid = "";
    private String job_uuid = "";
    private String group_uuid = "";
    private String role_id = "";
    private String contract_type = "";

    private String[] strings = {"拍照", "相册"};

    private ArrayList<String> contract = new ArrayList<>();


    private String uuid = "";

    private int type = 0;

    @Override
    public void initView(@Nullable Bundle savedInstanceState) {
        contract.add("退休返聘合同");
        contract.add("劳务合同");
        mUploadAdapter = new GridImageAdapter(getActivity());
        mUploadAdapter.setSelectMax(9);
        getMDatabind().upload.recyclerview.setAdapter(mUploadAdapter);
        getMDatabind().upload.recyclerview.setLayoutManager(new GridLayoutManager(getActivity(), 4));
        getMDatabind().upload.recyclerview.addItemDecoration(new MyGridSpacingItemDecoration(4, SizeUtils.dp2px(10), false));
        getMDatabind().upload.tvBaseUploadTitle.setText("合同照片");


        //隐藏箭头
        if (Constant.ROLE_MANGER || Constant.ROLE_HR) {
            getMDatabind().withProject.getArrowImageView().setVisibility(View.VISIBLE);
        } else {
            getMDatabind().withProject.getArrowImageView().setVisibility(View.GONE);
        }


        //入职 日前设置默认的日期
        getMDatabind().withStartDate.setTvRightText(TimeUtils.date2String(TimeUtils.getNowDate(), "yyyy-MM-dd"));
    }

    @Override
    public void lazyLoadData() {
        if (getArguments() != null) {//说明已经存在了
            uuid = getArguments().getString("uuid");
            type = getArguments().getInt("type");

            String application_no = getArguments().getString("application_no");

            HashMap<String, String> hashMap = new HashMap<>();
            if (!TextUtils.isEmpty(uuid)) {
                hashMap.put("uuid", uuid);
            }
            if (!TextUtils.isEmpty(application_no)) {
                hashMap.put("application_no", application_no);
            }
            hashMap.put("is_work_info", "1");
            //1是草稿编辑  2是草稿新建 3是档案详情
            if (type == 3) {
                mViewModel.requestStaffDetail(hashMap);//真正的详情
            } else {
                //再去获取小组列表，取最后一个
                mViewModel.requestMembersDetail(hashMap);//草稿的详情，还没真的成为员工
            }
        } else {//默认选中一波数据
            //如果是新增项目 那么项目列表 默认选择选中的项目
            if (App.appViewModelInstance.getProjectInfo().getValue() != null) {
                project_uuid = App.appViewModelInstance.getProjectInfo().getValue().getUuid();
                getMDatabind().withProject.setTvRightText(App.appViewModelInstance.getProjectInfo().getValue().getProject_short_name());
                mViewModel.requestGroupAll(1, project_uuid);//获取该项目下的所有岗位
            }
            //合约日期
            Calendar calendar = Calendar.getInstance(); // 获取当前时间的 Calendar 实例
            calendar.add(Calendar.YEAR, 1); // 将时间增加一年

            int year = calendar.get(Calendar.YEAR); // 获取增加后的年份
            int month = calendar.get(Calendar.MONTH) + 1; // 获取增加后的月份
            int day = calendar.get(Calendar.DAY_OF_MONTH); // 获取增加后的日期

            getMDatabind().withEndEnd.setTvRightText(year + "-" + month + "-" + day);
            //退休合同默认选中
            contract_type = "0";
            getMDatabind().withContractType.setTvRightText("退休返聘合同");
            role_id = "5";
            getMDatabind().withPermission.setTvRightText("保洁");
        }
    }

    @Override
    public void initObserver() {
        //新建的uuid
        App.appViewModelInstance.getCreateUuid().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                uuid = s;
            }
        });
        //监听什么权限
        App.appViewModelInstance.getSelectPermissionsStatus().observe(this, new Observer<PermissionData>() {
            @Override
            public void onChanged(PermissionData data) {
                role_id = data.getId();
                getMDatabind().withPermission.setTvRightText(data.getTitle());
            }
        });
        //监听项目
        App.appViewModelInstance.getSelectCompanyProjectMangerList().observe(this, new Observer<ProjectMangerList>() {
            @Override
            public void onChanged(ProjectMangerList data) {
                project_uuid = data.getUuid();
                getMDatabind().withProject.setTvRightText(data.getProject_name());
                getMDatabind().withWorkPost.setTvRightText(null);
                getMDatabind().tvGroupText.setText("");
                getMDatabind().tvClean.setVisibility(View.GONE);
                job_uuid = "";
                group_uuid = "";
            }
        });
        //坚挺小组
        App.appViewModelInstance.getSelectedGroup().observe(this, new Observer<GroupMangerListEntity>() {
            @Override
            public void onChanged(GroupMangerListEntity groupMangerListEntity) {
                group_uuid = groupMangerListEntity.getUuid();
                getMDatabind().tvGroupText.setText(groupMangerListEntity.getGroup_name());
                getMDatabind().tvClean.setVisibility(View.VISIBLE);
            }
        });
    }


    @Override
    public void onBindViewClick() {
        //apdater
        mUploadAdapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {

            }

            @Override
            public void openPicture() {
                showBottomSelectedPic(9);
            }
        });
        //选择项目
        getMDatabind().withProject.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Constant.ROLE_MANGER || Constant.ROLE_HR) {
                    Bundle bundle = new Bundle();
                    bundle.putBoolean("isSelected", true);
                    ActivityForwardUtil.startActivity(ProjectManagerActivity.class, bundle);
                }
            }
        });
        //选择岗位
        getMDatabind().withWorkPost.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(project_uuid)) {
                    ToastUtil.show("请先选择项目");
                    return;
                }
                mViewModel.requestJobList(project_uuid);
            }
        });

        //清空小组
        getMDatabind().tvClean.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                group_uuid = "";
                getMDatabind().tvGroupText.setText("");
                getMDatabind().tvClean.setVisibility(View.GONE);
            }
        });
        //所属小组
        getMDatabind().withGroup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putBoolean("isSelected", true);
                bundle.putString("project_uuid", project_uuid);
                ActivityForwardUtil.startActivity(GroupManagerActivity.class, bundle);
            }
        });
        //用工开始日期
        getMDatabind().withStartDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int startYear = 2000;
                Calendar defInstance = Calendar.getInstance();
                Calendar startInstance = null;
                if (!TextUtils.isEmpty(getMDatabind().withStartDate.getTvRight())) {
                    defInstance.setTime(TimeUtils.string2Date(getMDatabind().withStartDate.getTvRight(), "yyyy-MM-dd"));
                }

                if (MMKVHelper.getBoolean(ConstantMMVK.IS_ENTRY_BEFORE_TODAY, false)) {//是否不允许补入今日之前的入职信息 1是 2否
                    startYear = Integer.parseInt(TimeUtils.date2String(TimeUtils.getNowDate(), "yyyy"));//开始的日期
                    startInstance = Calendar.getInstance();
                }

                CommonUtils.showDialogTimePickerView(getMActivity(), "入职日期", defInstance, startYear, 2099, startInstance, null,
                        CustomTimePickerPopup.Mode.YMD, new OnDialogTimePickerListener() {
                            public void onTimeChanged(Date date) {
                            }

                            @Override
                            public void onTimeConfirm(Date date, View view) {
                                getMDatabind().withStartDate.setTvRightText(TimeUtils.date2String(date, "yyyy-MM-dd"));
                            }
                        });
            }
        });
        //用工结束日期
        getMDatabind().withEndEnd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Calendar defInstance = Calendar.getInstance();
                if (!TextUtils.isEmpty(getMDatabind().withEndEnd.getTvRight())) {
                    defInstance.setTime(TimeUtils.string2Date(getMDatabind().withEndEnd.getTvRight(), "yyyy-MM-dd"));
                } else {
                    //等于请选择的话，就根据当前的日期+1年
                    defInstance.add(Calendar.YEAR, 1); // 将当前日期增加一年
                    Date nextYearToday = defInstance.getTime();
                    defInstance.setTime(nextYearToday);
                }
                CommonUtils.showDialogTimePickerView(getMActivity(), "合约结束日期", defInstance, 2000, 2099, null, null, CustomTimePickerPopup.Mode.YMD, new OnDialogTimePickerListener() {
                    public void onTimeChanged(Date date) {
                    }

                    @Override
                    public void onTimeConfirm(Date date, View view) {
                        getMDatabind().withEndEnd.setTvRightText(TimeUtils.date2String(date, "yyyy-MM-dd"));
                    }
                });
            }
        });
        //系统的操作权限
        getMDatabind().withPermission.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("selectText", getMDatabind().withPermission.getTvRight());
                bundle.putString("channel", "2");
                ActivityForwardUtil.startActivity(PermissionsActivity.class, bundle);
            }
        });
        //合同类型
        getMDatabind().withContractType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CommonUtils.showDialogWheelSingleList(getMActivity(), "请选择合同类型", contract, getMDatabind().withContractType.getTvRight(), new OnDialogSelectListener() {
                    @Override
                    public void onSelect(int position, String text) {
                        contract_type = String.valueOf(position);
                        getMDatabind().withContractType.setTvRightText(text);
                    }
                });
            }
        });


        getMDatabind().bottom.butBottomButLast.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                App.appViewModelInstance.getProjectLastPersonnel().setValue(2);
            }
        });
        getMDatabind().bottom.butBottomButNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(getMDatabind().withProject.getTvRight())) {
                    ToastUtil.show("请选择项目");
                    return;
                }

                if (TextUtils.isEmpty(getMDatabind().withWorkPost.getTvRight())) {
                    ToastUtil.show("请选择岗位");
                    return;
                }

                if (TextUtils.isEmpty(getMDatabind().withStartDate.getTvRight())) {
                    ToastUtil.show("请选择用工开始日期");
                    return;
                }

                if (TextUtils.isEmpty(getMDatabind().withEndEnd.getTvRight())) {
                    ToastUtil.show("请选择用工结束日期");
                    return;
                }

                if (TextUtils.isEmpty(getMDatabind().withPermission.getTvRight())) {
                    ToastUtil.show("请选择系统操作权限");
                    return;
                }

                HashMap<String, String> hashMap = new HashMap<>();
                hashMap.put("op_type", "work_info");
                hashMap.put("uuid", uuid);
                hashMap.put("project_uuid", "" + project_uuid);
                hashMap.put("job_uuid", "" + job_uuid);
                if (!TextUtils.isEmpty(group_uuid)) {
                    hashMap.put("group_uuid", "" + group_uuid);
                }
                hashMap.put("work_start_time", "" + getMDatabind().withStartDate.getTvRight());
                hashMap.put("work_end_time", "" + getMDatabind().withEndEnd.getTvRight());
                hashMap.put("role_id", "" + role_id);
                hashMap.put("contract_type", "" + contract_type);
                if (mUploadAdapter.getData().size() > 0) {
                    hashMap.put("contract_pic", "" + JSON.toJSONString(mUploadAdapter.getData()));
                }
                mViewModel.requestUpdateMembers(hashMap, AddProjectActivity.ID_WORK_INFO, type);
            }
        });
    }

    @Override
    public void onRequestSuccess() {
        mViewModel.getGroupMangerEntity().observe(this, new Observer<GroupMangerEntity>() {
            @Override
            public void onChanged(GroupMangerEntity groupMangerEntity) {
                LogUtils.e("有值 - " + groupMangerEntity.getList().size());
                //默认取 list 最后一个
                if (groupMangerEntity.getList().size() > 0) {
                    GroupMangerListEntity entity = groupMangerEntity.getList().get(groupMangerEntity.getList().size() - 1);
                    if (entity != null) {
                        group_uuid = entity.getUuid();
                        getMDatabind().tvGroupText.setText(entity.getGroup_name());
                        getMDatabind().tvClean.setVisibility(View.VISIBLE);
                    }
                }
            }
        });

        mViewModel.getUpdateWorkInfoStatus().observe(this, new Observer<IDCardMemberEntity>() {
            @Override
            public void onChanged(IDCardMemberEntity idCardMemberEntity) {
                App.appViewModelInstance.getProjectPersonnel().setValue(4);
            }
        });

        mViewModel.getJobManger().observe(this, new Observer<JobEntity>() {
            @Override
            public void onChanged(JobEntity jobEntity) {
                if (jobEntity != null) {

                    ArrayList<String> works = new ArrayList<>();
                    for (JobListEntity list : jobEntity.getList()) {
                        works.add(list.getJob_name());
                    }
                    CommonUtils.showDialogWheelSingleList(getMActivity(), "请选择岗位", works, getMDatabind().withWorkPost.getTvRight(), new OnDialogSelectListener() {
                        @Override
                        public void onSelect(int position, String text) {
                            job_uuid = jobEntity.getList().get(position).getUuid();
                            getMDatabind().withWorkPost.setTvRightText(text);
                            MMKVHelper.putString(ConstantMMVK.WORK_JOB_SALARY, jobEntity.getList().get(position).getJob_salary());
                        }
                    });
                }
            }
        });


        mViewModel.getMembersDetailEntity().observe(this, new Observer<MembersDetailEntity>() {
            @Override
            public void onChanged(MembersDetailEntity membersDetailEntity) {
                uuid = membersDetailEntity.getUuid();
                fillData(membersDetailEntity.getWork_info());
            }
        });
    }

    private void fillData(WorkInfoEntity workInfo) {
        if (workInfo != null) {
            project_uuid = workInfo.getProject_uuid();
            job_uuid = workInfo.getJob_uuid();
            group_uuid = workInfo.getGroup_uuid();
            role_id = workInfo.getRole_id();
            contract_type = workInfo.getContract_type();
            if (!TextUtils.isEmpty(workInfo.getWork_start_time())) {
                getMDatabind().withStartDate.setTvRightText(workInfo.getWork_start_time());
            } else {
                getMDatabind().withStartDate.setTvRightText(TimeUtils.date2String(TimeUtils.getNowDate(), "yyyy-MM-dd"));
            }
            getMDatabind().withEndEnd.setTvRightText(workInfo.getWork_end_time());
            getMDatabind().withProject.setTvRightText(workInfo.getProject_name());
            getMDatabind().withWorkPost.setTvRightText(workInfo.getJob_name());
            getMDatabind().tvGroupText.setText(workInfo.getGroup_name());
            getMDatabind().withPermission.setTvRightText(workInfo.getRole_name());
            getMDatabind().withContractType.setTvRightText(workInfo.getContract_type_name());
            for (int i = 0; i < workInfo.getPic_list().size(); i++) {
                mUploadAdapter.addItemData(workInfo.getPic_list().get(i).getSource_url());
            }

            if (!TextUtils.isEmpty(getMDatabind().tvGroupText.getText())) {
                getMDatabind().tvClean.setVisibility(View.VISIBLE);
            } else {
                getMDatabind().tvClean.setVisibility(View.GONE);
            }
        }
        if (type != 3) {
            //如果是新增项目 那么项目列表 默认选择选中的项目
            if (App.appViewModelInstance.getProjectInfo().getValue() != null && TextUtils.isEmpty(workInfo.getProject_name())) {
                project_uuid = App.appViewModelInstance.getProjectInfo().getValue().getUuid();
                getMDatabind().withProject.setTvRightText(App.appViewModelInstance.getProjectInfo().getValue().getProject_short_name());
                mViewModel.requestGroupAll(1, project_uuid);//获取该项目下的所有岗位
            }
            //合约日期
            if (TextUtils.isEmpty(workInfo.getWork_end_time())) {

                Calendar calendar = Calendar.getInstance(); // 获取当前时间的 Calendar 实例
                calendar.add(Calendar.YEAR, 1); // 将时间增加一年

                int year = calendar.get(Calendar.YEAR); // 获取增加后的年份
                int month = calendar.get(Calendar.MONTH) + 1; // 获取增加后的月份
                int day = calendar.get(Calendar.DAY_OF_MONTH); // 获取增加后的日期

                getMDatabind().withEndEnd.setTvRightText(year + "-" + month + "-" + day);
            }
            //退休合同默认选中
            if (TextUtils.isEmpty(workInfo.getContract_type_name())) {
                contract_type = "0";
                getMDatabind().withContractType.setTvRightText("退休返聘合同");
            }
            if (TextUtils.isEmpty(workInfo.getRole_name())) {
                role_id = "5";
                getMDatabind().withPermission.setTvRightText("保洁");
            }
        }
    }


    private void uploadMedias(ArrayList<LocalMedia> result) {
        ArrayList<String> strings1 = new ArrayList<>();
        for (int i = 0; i < result.size(); i++) {
            strings1.add(result.get(i).isCompressed() ? result.get(i).getCompressPath() : result.get(i).getRealPath());
        }
        UploadFileHelper.getInstance().uploadFiles(getActivity(), strings1, UploadFileHelper.PATH_HEADER_PERSONNEL, new UploadFileHelper.UploadListener() {
            @Override
            public void onUploadSuccess(String response) {
                mUploadAdapter.addItemData(response);
            }

            @Override
            public void onUploadFailed(String error) {

            }

            @Override
            public void onUploadProgress(int progress) {

            }

        });
    }

    private void showBottomSelectedPic(int size) {
        CommonUtils.showBottomListWith(getActivity(), 20, "", strings, new OnSelectListener() {
            @Override
            public void onSelect(int position, String text) {
                switch (position) {
                    case 0:
                        ChoosePicUtil.openCameraTake(getMActivity(), new OnResultCallbackListener<LocalMedia>() {
                            @Override
                            public void onResult(ArrayList<LocalMedia> result) {
                                uploadMedias(result);
                            }

                            @Override
                            public void onCancel() {

                            }
                        });
                        break;
                    case 1:
                        ChoosePicUtil.openAlbum(getMActivity(), size, new OnResultCallbackListener<LocalMedia>() {
                            @Override
                            public void onResult(ArrayList<LocalMedia> result) {
                                uploadMedias(result);
                            }

                            @Override
                            public void onCancel() {

                            }
                        });
                        break;
                }
            }
        });
    }
}
